#!/usr/bin/env python
import os
import jinja2
import logging
from modules.box import Box
from modules.Predef import Predef as PRE
from google.appengine.api import users

class Main:
        
    ####################################################
    # Initialize
    ####################################################
    def __init__(self, context):
        self.context=context
        #self.request=request
        #self.response=response
        self.message=''
        self.errmessage=''

        self.door=self.context.request.get('doorplate')

    ####################################################
    # For message
    ####################################################
    def MESSAGE(self,m):
        self.message=PRE.genMessage(self.message,m)

    def ERRMESSAGE(self,m):
        self.errmessage=PRE.genMessage(self.errmessage,"ERROR:"+m)

    ####################################################
    # Show the content
    ####################################################
    def getContent(self, t):
        temp_path=os.path.join(
                os.path.dirname(__file__),
                "../templates/")

        temp=jinja2.Environment(loader=jinja2.FileSystemLoader(temp_path)).get_template(t)

        user = users.get_current_user()
        if user:
            u = '%s <a href="%s"> sign out </a>' % ( user.nickname(), users.create_logout_url("/"))
            logging.info(u)
        else:
            u = 'guest'
        # for main page
        if self.door == '':
            return temp.render(
                    {
                        'doors':PRE.doors,
                        'user': u,
                        })
        # came in to door
        else:
            return temp.render(
                    {
                        'doors':PRE.doors,
                        'user': u,
                        'candidates':self.candidates,
                        'doorplate':self.door,
                        'e':self.errmessage,
                        'm':self.message,
                        })


    ####################################################
    # Read and Check settings to GET
    ####################################################
    def doGet(self):
        if self.door == '':
            self.context.response.out.write(self.getContent('main.html'))
        else:
            self.candidates=Box.listBoxes(self.door==PRE.doors[0])
            self.context.response.out.write(self.getContent('door.html'))

    ####################################################
    # Read and Check settings to POST
    ####################################################
    def doPost(self):
        if self.door == '':
            self.context.response.out.write(self.getContent('main.html'))
        else:

            for k in Box.listBoxes(self.door==PRE.doors[0]):
                if self.context.request.get('hidden_'+k.label) == 'Deleted':
                    Box.delBox(k.label)
                    self.MESSAGE('Success: "{}" has been deleted!'.format(k.label))

            self.candidates=Box.listBoxes(self.door==PRE.doors[0])

            label=self.context.request.get('newlabel')

            if (label!=''):

                if Box.getBox(label):
                    self.ERRMESSAGE('"{}" has existed in current list'.format(label))
                else:
                    self.context.redirect('/cell?label='+label)

            self.context.response.out.write(self.getContent('door.html'))
